package com.liao.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.liao.mapper.UserMapper;
import com.liao.po.Goods;
import com.liao.po.User;
import com.liao.service.UserService;
import com.liao.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private Integer page = 1;
    private Integer limit = 10;

    @Override
    public User findById(String username, String password) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        userLambdaQueryWrapper.eq(User::getPassword,password);
        return this.baseMapper.selectOne(userLambdaQueryWrapper);
    }

    @Override
    public PageUtils queryPageByCodition(Map<String, Object> params) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.lambdaQuery();

        String pagekey = (String) params.get("page");
        if (!StringUtils.isEmpty(pagekey) && !"0".equalsIgnoreCase(pagekey)) {
            page = Integer.parseInt(pagekey);
        }

        String limitkey = (String) params.get("limit");
        if (!StringUtils.isEmpty(limitkey) && !"0".equalsIgnoreCase(limitkey)) {
            limit = Integer.parseInt(limitkey);
        }

        String sexKey = (String) params.get("sex");
        if (!StringUtils.isEmpty(sexKey) ) {
            userLambdaQueryWrapper.eq(User::getSex,sexKey);
        }

        String searchKey = (String) params.get("searchkey");
        if (!StringUtils.isEmpty(searchKey)) {
            userLambdaQueryWrapper.and(wq ->wq.like(User::getUid, searchKey).or().like(User::getUsername, searchKey).or().like(User::getPhone, searchKey).or().like(User::getRealname, searchKey).or().like(User::getEmail, searchKey));
        }


        String isLockKey = (String) params.get("isLock");
        if (!StringUtils.isEmpty(isLockKey)) {
            userLambdaQueryWrapper.eq(User::getIsLock, isLockKey);
        }


        Page<User> userPage = new Page<>(page , limit);
        IPage<User> userIPage = this.baseMapper.selectPage(userPage , userLambdaQueryWrapper);
        System.out.println("总页数： "+userIPage.getPages());
        System.out.println("总记录数： "+userIPage.getTotal());
        userIPage.getRecords().forEach(System.out::println);
        return new PageUtils(userIPage);
    }
}
